package com.us.usws.support.uitls;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * json data opration util
 * @author fengyong
 *
 */
public class JSONDataUtil {

	private static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * get string from object
	 * @param obj
	 * @return
	 */
	public static String jsonStringfromObject(Object obj) {

		StringWriter sw = new StringWriter();
		String jsonString = "";
		try {
			objectMapper.writer(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).writeValue(sw, obj);
			jsonString = sw.toString();
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				sw.close();
				sw = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jsonString;
	}

	/**
	 * get json string for ext
	 * @param obj
	 * @param totalCount
	 * @return
	 */
	public static String extJsonSupportPage(Object obj, int totalCount) {
		jsonStringfromObject(obj);
		String json = "{'rows':" + jsonStringfromObject(obj) + ", 'totalCount':" + totalCount + "}";
		return json;
	}
}
